package com.sovphone.clevertools

import android.content.Context
import android.os.*
import android.text.TextUtils
import android.util.Log
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.concurrent.LinkedBlockingDeque

/**
 * Author tianwei
 * Date：2020/12/5 9:10
 *
 * Description:
 */
class Logger private constructor() {

    companion object {
        fun getInstance(): Logger = LoggerHolder.instance
    }

    object LoggerHolder {
        var instance: Logger = Logger()
    }

    private var mQueue: LinkedBlockingDeque<String>? = null
    private var mHandlerThread: HandlerThread? = null
    private var writeHandler: WriteHandler? = null
    private var running: Boolean = false

    private var mContext: Context? = null

    fun init(mContext: Context) {
        this.mContext = mContext.applicationContext
        mQueue = LinkedBlockingDeque()
        mHandlerThread = HandlerThread("log")
        mHandlerThread?.start()
        writeHandler = WriteHandler(mHandlerThread?.looper!!)
    }

    fun destroy() {
        running = false
        writeHandler?.removeCallbacksAndMessages(null)
        writeHandler = null
        mHandlerThread?.quit()
        mHandlerThread = null
        mQueue?.clear()
        mQueue = null
    }

    private inner class WriteHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            Log.e("Logger", "handleMessage")
            while (running) {
                val msg = mQueue?.take()
                if (!TextUtils.isEmpty(msg)) {
                    writeLog(msg!!)
                }
            }
        }
    }

    fun log(msg: String) {
        mQueue?.offer(msg)
        if (!running) {
            running = true
            writeHandler?.sendEmptyMessage(0)
        }
    }

    private fun writeLog(msg: String) {
        var msg = " ${DateUtils.format(
            System.currentTimeMillis(),
            "yyyy-MM-dd HH:mm:ss:sss"
        )}  " + msg

        Log.e(
            "Logger", "${Thread.currentThread().name}:" + msg
        )
        var os: FileOutputStream? = null
        var fileName =
            "muyu" + DateUtils.format(System.currentTimeMillis(), "yyyyMMddHHmmss") + ".log"
        try {
            val dir = File(Environment.getExternalStorageDirectory().path + "/muyu/")
            if (!dir.exists()) {
                dir.mkdirs()
            }
            Log.e("Logger", "${dir.exists()}")
            val file = File(dir, fileName)
            if (!file.exists()) {
                file.parentFile.mkdirs()
                file.createNewFile()
            }
            os = FileOutputStream(file)
            os.write(msg.toByteArray())
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                os?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

    }
}